classdef NewtonSolver < handle
    %NewtonSolver Summary of this class goes here
    %   Detailed explanation goes here
    
    properties
        F           %function handle 
        F_p         %function derivative handle
        X0          %initial X value
        X           %vector of positions
        TolF=.01;        %Tolerence in Function
        TolX=.01;        %Tolerence in X
    end
    
    methods
        
        function  newtonupdate(obj)
                
            obj.X(1)=obj.X0;
            ii=1;
            dX=2*obj.TolX;
            dF=2*obj.TolF;
            
            while (dX>obj.TolX)||(dF>obj.TolF)
                CurrentX=obj.X(ii);
                NewX=CurrentX-obj.F(CurrentX)/obj.F_p(CurrentX);
                dX=abs(CurrentX-NewX);
                dF=abs( obj.F(CurrentX)-obj.F(NewX));
                ii=ii+1;
                obj.X(ii)=NewX; 
            end
        end
        
        function plotUpdates(obj)
            
            figure;
            hold on
            for ii=1:length(obj.X)-1
               x_start=obj.X(ii);
               x_end=obj.X(ii+1)
               y_start=obj.F(obj.X(ii));
               y_end=obj.F(obj.X(ii+1));
               hr=plot([x_start, x_end],[y_start, y_end],'r','linewidth',2)
               s=sprintf('X%d',ii-1)
               text(x_start,y_start,s)
            end
            
            %plot function
            
            xmin=min(obj.X)
            xmax=max(obj.X)
            interval=abs(xmin-xmax);
            
            xvec=linspace(xmin-interval,xmax+interval)
            h=plot(xvec,obj.F(xvec),'b')
            plot(xvec,xvec*0,'k--')
            
            xlabel('X')
            ylabel('f(X)')
            
            h.DisplayName='Function'
            hr.DisplayName='Newton Updates'
            legend([h,hr])
            
        end
        
        
        
    end
    
end

